package org.example.lethear.utils;

import org.example.lethear.security.UserDetailsImpl;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;

/**
 * 安全工具类
 * 用于获取当前登录用户信息
 */
public class SecurityUtils {
    
    /**
     * 获取当前认证信息
     */
    public static Authentication getCurrentAuthentication() {
        return SecurityContextHolder.getContext().getAuthentication();
    }
    
    /**
     * 获取当前用户详情
     */
    public static UserDetailsImpl getCurrentUserDetails() {
        Authentication authentication = getCurrentAuthentication();
        if (authentication != null && authentication.getPrincipal() instanceof UserDetailsImpl) {
            return (UserDetailsImpl) authentication.getPrincipal();
        }
        return null;
    }
    
    /**
     * 获取当前用户ID
     */
    public static Long getCurrentUserId() {
        UserDetailsImpl userDetails = getCurrentUserDetails();
        return userDetails != null ? userDetails.getId() : null;
    }
    
    /**
     * 检查当前用户是否有指定角色
     */
    public static boolean hasRole(String role) {
        UserDetailsImpl userDetails = getCurrentUserDetails();
        return userDetails != null && userDetails.hasRole(role);
    }
    
    /**
     * 检查当前用户是否为管理员（包括普通管理员和系统管理员）
     */
    public static boolean isAdmin() {
        return hasRole("ADMIN") || hasRole("SYSTEM_ADMIN");
    }
    
    /**
     * 检查当前用户是否为系统管理员
     */
    public static boolean isSystemAdmin() {
        return hasRole("SYSTEM_ADMIN");
    }
    
    /**
     * 检查当前用户是否为普通用户
     */
    public static boolean isUser() {
        return hasRole("USER");
    }
} 